/**
 * Created by Administrator on 2017/3/21.
 */
import React, { Component } from 'react';
import { Form, Input, DatePicker, Select, InputNumber, Button, Tooltip, Icon, message } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import request from '@/utils/request';
import find from 'lodash/find';
import filter from 'lodash/filter'

const FormItem = Form.Item;
const Option = Select.Option;
let uuid = 1;

class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      itemArr: [1],
      itemActiveKey: ['1'],
      all_department:[],
      staff1:[],
    };
  }

  fetchAllDepartments=()=>{
    const that = this;
    request(`/all_departments`, {
      method: 'GET',
      params: {
        order_direction: 'desc',
      },
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          all_department: response.data.data,
        });
      }
    });
  }

  componentDidMount() {
    this.fetchAllDepartments();
    const that=this
    if(this.props.editRecord){
      const sortData=this.props.editRecord.reviewers;
      uuid=sortData.length
      this.setState({
        itemArr:sortData.map((item,index)=>{
          return index+1
        }),
        itemActiveKey:sortData.map((item,index)=>{
          return (index+1).toString()
        }),
      })
      for(let i=0;i<sortData.length;i++){
        this.setState({
          [`staff${i+1}`]:[],
        },function() {
          that.handleChange(sortData[i].department_id,i+1)
          that.props.form.setFieldsValue({
            [`item_number-${this.props.sort}-${i+1}`]:sortData[i].department_id,
            [`staff_id-${this.props.sort}-${i+1}`]:sortData[i].user_id,
          })
        })
      }
    }
  }

  addItem = () => {
    uuid++;
    this.state.itemArr.push(uuid);
    this.state.itemActiveKey.push(uuid.toString());
    this.setState({
      [`item${uuid}`]: [],
      [`staff${uuid}`]: [],
      itemArr: this.state.itemArr,
      itemActiveKey: this.state.itemActiveKey,
    },function(){
    });
  };
  deleteItem = (item) => {
    console.log('删除的item', item);
    if (this.state.itemArr.length === 1) {
      console.log('只有一个审批人');
      message.error('至少需要一个审批人')
      return false
    }
    const index = this.state.itemArr.indexOf(item);
    console.log('index', index);
    this.state.itemArr.splice(index, 1);
    this.setState({
      itemArr: this.state.itemArr,
    });
  };
  handleChange = (value, item) => {
    //item 从1开始
    console.log(value);
    console.log(this.state[`item${item}`]);
    const that = this;
    request(`/staffs`, {
      method: 'GET',
      params:{
        department_id:value,
        per_page:100
      }
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          [`staff${item}`]:response.data.data,
        })
      }
    });


  };

  render() {

    const { getFieldDecorator } = this.props.form;
    const itemForms = this.state.itemArr.map((item, index) => {
      console.log('item',item.status)
      return (
        <div style={{ display: 'flex',height:'31px' }} className={'custom-table-form'} key={index} layout="inline">
          <div style={{ width: '50px', lineHeight: '29px', textAlign: 'center', border: '1px solid #d9d9d9' }}>
            {index + 1}
          </div>
          <FormItem
            style={{ flex: '1', marginRight: '0', width: '100%' }}
          >
            {getFieldDecorator(`item_number-${this.props.sort}-${item}`, {
              initialValue: '',
            })(
              <Select
                style={{ width: this.props.columnWidth }}
                onChange={(value) => this.handleChange(value, `${item}`)}
              >
                {this.state.all_department.map((item, index2) => {
                  return <Option key={index2} value={item.id}>{item.name}</Option>;
                })}
              </Select>,
            )}
          </FormItem>
          <FormItem
            style={{ flex: '1', marginRight: '0' }}
          >
            {getFieldDecorator(`staff_id-${this.props.sort}-${item}`, {
              initialValue: '',
            })(
              <Select
                style={{ width: this.props.columnWidth }}
              >
                {this.state[`staff${item}`].map((item, index2) => {
                  return <Option key={index2} value={item.id}>{item.name}</Option>;
                })}
              </Select>,
            )}
          </FormItem>
          <div style={{ width: '80px', lineHeight: '29px', textAlign: 'center', border: '1px solid #d9d9d9' }}>
            <Button
              style={{ height: '22px' }}
              type="danger"
              size="small"
              icon="delete"
              disabled={this.props.editRecord.reviewers[index]?Boolean(this.props.editRecord.reviewers[index].status===4):false}
              onClick={(e) => {
                e.stopPropagation();
                this.deleteItem(item);
              }
              }
            >删除
            </Button>
          </div>


        </div>
      );
    });
    return (
      <div>
        <div style={{ border: '1px solid #d9d9d9', marginTop: '10px' }}>

          <div style={{
            display: 'flex',
            fontWeight: 'bold',
            lineHeight: '32px',
            height: '32px',
            background: 'rgb(249,249,249)',
          }}>
            <div style={{ width: '50px', paddingLeft: '10px', border: '1px solid #d9d9d9' }}>序号</div>
            <div style={{ flex: '1', paddingLeft: '10px', border: '1px solid #d9d9d9' }}>审批部门</div>
            <div style={{ flex: '1', paddingLeft: '10px', border: '1px solid #d9d9d9' }}>审批人</div>
            <div style={{ width: '80px', paddingLeft: '10px', border: '1px solid #d9d9d9' }}>操作</div>
          </div>
          {itemForms}
          <Button type={'primary'} className={'btn-cyan'} icon={'plus'} block onClick={this.addItem}>添加审批人</Button>

        </div>
      </div>

    );
  }
}

export default connect()(AddPoliciesForm);
